<template>
  <div>
    <div style="width: 100%">
      <t-table
        row-key="id"
        :data="costList"
        :columns="props.type==='3'?columnsLaborTable:columnsTypeTable"
        bordered
        size="small"
        stripe
        hover
      >
        <template #fileUrl="{ row, rowIndex }">
          <t-form-item
            label="封面图"
            :name="`costList[${rowIndex}].fileUrl`"
            :rules="[{ required: false, message: '请选择封面图' }]"
            label-width="0"
          >
            <image-viewer :images="[row.fileUrl]" width="80px" height="80px" v-if="row.fileUrl" />
          </t-form-item>
        </template>
        <template #num="{ row, rowIndex }">
          <t-form-item
            label="数量"
            :name="`costList[${rowIndex}].num`"
            :rules="[{ required: false, message: '请输入数量' }]"
            label-width="0"
            
          >
          <t-input-number
            v-model:value="row.num"
            placeholder="请输入数量"
            clearable
            :readonly="readonly"
            style="width: 100%"
            :min="1"
            :decimal-places="2"
            @change="handleChangeNum"
          />
          </t-form-item>
        </template>
        <template #houseType="{ row, rowIndex }">
          <t-form-item
            label="房屋类型"
            :name="`costList[${rowIndex}].houseType`"
            :rules="[{ required: false, message: '请输入房屋类型' }]"
            label-width="0"
          >
          {{dictionaryStore.analysis('decoration_order_house_type', row.houseType)}}
          </t-form-item>
        </template>
        <template #unit="{ row, rowIndex }">
          <t-form-item
            label="单位"
            :name="`costList[${rowIndex}].unit`"
            :rules="[{ required: false, message: '请输入单位' }]"
            label-width="0"
          >
          {{dictionaryStore.analysis('unit', row.unit)}}
          </t-form-item>
        </template>
      
        <template #operation="{ rowIndex }">
          <t-popconfirm
            v-if="!readonly"
            content="确认要删除该项吗？"
            @confirm="handleDelete(rowIndex)"
          >
            <t-link theme="danger"> 删除 </t-link>
          </t-popconfirm>
        </template>
      </t-table>
      <t-button v-if="!readonly" block @click="handleSelect" > 添加成本 </t-button>
    </div>
    <!-- 选择对话框 -->
    <cost-selection-dialog
      v-model:visible="visibleMessage"
      :type="props.type"
      @save="handleSave"
    />
  </div>
</template>

<script setup lang="ts">
import {  ref, onMounted, useTemplateRef, computed, watch } from 'vue';
import { MessagePlugin, TableCol, TreeNodeModel } from 'tdesign-vue-next';
import ImageViewer from '@/components/image-viewer/index.vue';
import CostSelectionDialog from './CostSelectionDialog.vue';
import { useDictionaryStore } from '@/store';

// 字典仓库
const dictionaryStore = useDictionaryStore();

// 组件 props
const props = defineProps({
  costList: {
    type: Array,
    default: [],
  },
  readonly: {
    type: Boolean,
    default: false,
  },
  // 主材、辅材、人工
  type: {
    type: String,
    require: true
  },
});

// 组件 emits
const emits = defineEmits(['update:costList']);

// 控制对话框显示
const visibleMessage = ref(false);



// 选择列表
const messageList = ref<Record<string, any>[]>([]);


const handleChangeNum = () => {
  emits('update:costList', messageList.value);  
}
const handleSelect = () => {
  visibleMessage.value = true;
};

const handleSave = (selectedData: any[]) => {
  console.log(selectedData,'se');
  console.log(messageList,'se');
  
    // 过滤掉已存在的数据
    const newData = selectedData.filter((selectedItem) => {
    return !messageList.value.some((existingItem) => existingItem.materialId == selectedItem.materialId);
  });
  messageList.value = [...messageList.value, ...newData]
  emits('update:costList', messageList.value);
};

// 处理删除
const handleDelete = (rowIndex: number) => {
  messageList.value.splice(rowIndex, 1)
  emits('update:costList', messageList.value);
};



// columns
const columnsLaborTable: TableCol[] = [
  // { colKey: 'projectName', title: '项目类型' },
  { colKey: 'houseType', title: '房屋类型' },
  { colKey: 'unit', title: '单位' },
  { colKey: 'costPrice', title: '单价(元)' },
  { colKey: 'remark', title: '备注' },
  { colKey: 'num', title: '数量',width:180 },
  { colKey: 'operation', title: '操作', width: 100, fixed: 'right' },
].map(column => ({ ...column, align: 'center' }));
// columns
const columnsTypeTable: TableCol[] = [
  { colKey: 'fileUrl', title: '封面图' },
  { colKey: 'name', title: '材料名称' },
  { colKey: 'unit', title: '单位' ,width:70},
  { colKey: 'brandName', title: '品牌名称',width:90 },
  { colKey: 'specifications', title: '规格',width:80 },
  // { colKey: 'materialNo', title: '材料编码' },
  { colKey: 'model', title: '型号',width:90 },
  { colKey: 'costPrice', title: '成本价(元)',width:90 },
  // { colKey: 'sellingPrice', title: '售价(元)' },
  { colKey: 'num', title: '数量',width:180 },
  { colKey: 'operation', title: '操作', fixed: 'right' },
].map(column => ({ ...column, align: 'center' }));
// 监听 props.costList 的变化，同步到 messageList
watch(
  () => props.costList,
  (newVal) => {
    messageList.value = [...newVal];
  },
  { immediate: true } // 立即执行一次
);

</script>

<style lang="less" scoped>
.container {
  display: flex;
  justify-content: flex-start;
  align-items: flex-start;

  @leftWidth: 300px;

  .left {
    width: @leftWidth;
  }

  .right {
    width: calc(100% - @leftWidth);
  }
}
</style>